package io.renren.modules.sys.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.AccountEntity;
import io.renren.modules.sys.entity.AccountheadEntity;
import io.renren.modules.sys.entity.InoutitemEntity;
import io.renren.modules.sys.service.AccountService;
import io.renren.modules.sys.service.InoutitemService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.entity.AccountitemEntity;
import io.renren.modules.sys.service.AccountitemService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 财务子表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-22 14:29:35
 */
@RestController
@RequestMapping("sys/accountitem")
public class AccountitemController {
    @Autowired
    private AccountitemService accountitemService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private InoutitemService inoutitemService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:accountitem:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = accountitemService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:accountitem:info")
    public R info(@PathVariable("id") Long id){
        AccountitemEntity accountitem = accountitemService.selectById(id);

        return R.ok().put("accountitem", accountitem);
    }

    /**
     * 根据id查询信息
     */
    @RequestMapping("/findBy")
    public R findBy(@RequestParam("HeaderId") Long id){
        EntityWrapper<AccountitemEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("HeaderId", id);
        List<AccountitemEntity> itemList = accountitemService.selectList(wrapper);

        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if (null != itemList) {
            for (AccountitemEntity accountItem : itemList) {
                JSONObject item = new JSONObject();
                item.put("Id", accountItem.getId());
                item.put("AccountId", accountItem.getAccountid() == null ? "" : accountItem.getAccountid());
                item.put("AccountName", accountItem.getAccountid() == null ? "" : accountService.selectById(accountItem.getAccountid()).getName());
                item.put("InOutItemId", accountItem.getInoutitemid() == null ? "" : accountItem.getInoutitemid());
                item.put("InOutItemName", accountItem.getInoutitemid() == null ? "" : inoutitemService.selectById(accountItem.getInoutitemid()).getName());
                Double eachAmount = accountItem.getEachamount();
                item.put("EachAmount", eachAmount < 0 ? 0 - eachAmount : eachAmount);
                item.put("Remark", accountItem.getRemark());
                item.put("op", 1);
                dataArray.add(item);
            }
        }

        return R.ok().put("total", dataArray.size()).put("rows", dataArray);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:accountitem:save")
    public R save(@RequestBody AccountitemEntity accountitem){
        accountitemService.insert(accountitem);

        return R.ok();
    }

    /**
     * saveDetails
     * Inserted: [{"InOutItemName":"利息收入","InOutItemId":"7","AccountId":"","EachAmount":"100","Remark":"www"}]
     * Deleted: []
     * Updated: []
     * HeaderId: 9
     * ListType: 收入
     */
    @RequestMapping("/saveDetails")
    public R saveDetails(@RequestParam Map params){
        Long headerId = 0L;
        String listType = "";
        String inserted = "";
        String deleted = "";
        String updated = "";
        if(params != null){
            headerId = Long.parseLong(params.get("HeaderId").toString());
            listType = (String)params.get("ListType"); //单据类型
            inserted = (String)params.get("Inserted");
            deleted = (String)params.get("Deleted");
            updated = (String)params.get("Updated");
        }
        //转为json
        JSONArray insertedJson = JSONArray.fromObject(inserted);
        JSONArray deletedJson = JSONArray.fromObject(deleted);
        JSONArray updatedJson = JSONArray.fromObject(updated);

        if (0 != insertedJson.size()) {
            /**
             * [{"InOutItemName":"全车贴膜-普通","InOutItemId":"12","AccountId":"","EachAmount":"1000","Remark":"aaa"}]
             */
            for (int i = 0; i < insertedJson.size(); i++) {
                AccountitemEntity accountItem = new AccountitemEntity();
                JSONObject tempInsertedJson = JSONObject.fromObject(insertedJson.get(i));
                accountItem.setHeaderid(headerId);
                if (tempInsertedJson.get("AccountId") != null && !tempInsertedJson.get("AccountId").equals("")) {
                    accountItem.setAccountid(tempInsertedJson.getLong("AccountId"));
                }
                if (tempInsertedJson.get("InOutItemId") != null && !tempInsertedJson.get("InOutItemId").equals("")) {
                    accountItem.setInoutitemid(tempInsertedJson.getLong("InOutItemId"));
                }
                if (tempInsertedJson.get("EachAmount") != null && !tempInsertedJson.get("EachAmount").equals("")) {
                    Double eachAmount = tempInsertedJson.getDouble("EachAmount");
                    if (listType.equals("付款")) {
                        eachAmount = 0 - eachAmount;
                    }
                    accountItem.setEachamount(eachAmount);
                } else {
                    accountItem.setEachamount(0.0);
                }
                accountItem.setRemark(tempInsertedJson.getString("Remark"));
                accountitemService.insert(accountItem);
            }
        }

        if (0 != deletedJson.size()) {
            for (int i = 0; i < deletedJson.size(); i++) {
                JSONObject tempDeletedJson = JSONObject.fromObject(deletedJson.get(i));
                accountitemService.deleteById(tempDeletedJson.getLong("Id"));
            }
        }

        if (0 != updatedJson.size()) {
            for (int i = 0; i < updatedJson.size(); i++) {
                JSONObject tempUpdatedJson = JSONObject.fromObject(updatedJson.get(i));
                AccountitemEntity accountItem = accountitemService.selectById(tempUpdatedJson.getLong("Id"));
                accountItem.setHeaderid(headerId);
                if (tempUpdatedJson.get("AccountId") != null && !tempUpdatedJson.get("AccountId").equals("")) {
                    accountItem.setAccountid(tempUpdatedJson.getLong("AccountId"));
                }
                if (tempUpdatedJson.get("InOutItemId") != null && !tempUpdatedJson.get("InOutItemId").equals("")) {
                    accountItem.setInoutitemid(tempUpdatedJson.getLong("InOutItemId"));
                }
                if (tempUpdatedJson.get("EachAmount") != null && !tempUpdatedJson.get("EachAmount").equals("")) {
                    Double eachAmount = tempUpdatedJson.getDouble("EachAmount");
                    if (listType.equals("付款")) {
                        eachAmount = 0 - eachAmount;
                    }
                    accountItem.setEachamount(eachAmount);
                } else {
                    accountItem.setEachamount(0.0);
                }
                accountItem.setRemark(tempUpdatedJson.getString("Remark"));
                accountitemService.updateAllColumnById(accountItem);
            }
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:accountitem:update")
    public R update(@RequestBody AccountitemEntity accountitem){
        ValidatorUtils.validateEntity(accountitem);
        accountitemService.updateAllColumnById(accountitem);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:accountitem:delete")
    public R delete(@RequestBody Long[] ids){
        accountitemService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

}
